FROM node:18-alpine

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm install --legacy-peer-deps

# Fix ajv dependency issue
RUN npm install ajv@^8.0.0 --legacy-peer-deps

# Copy source code
COPY . .

# Create .env file if not exists
RUN echo "REACT_APP_API_URL=http://backend:8000" > .env

# Set Node environment to production and handle potential build issues
ENV NODE_OPTIONS=--max-old-space-size=4096
ENV GENERATE_SOURCEMAP=false

# Build the application with fallback handling
RUN npm run build || (echo "Build failed, trying to resolve dependency issues..." && npm install ajv@^6.12.6 ajv-keywords@^3.5.2 --legacy-peer-deps && npm run build)

# Install serve to run the built app
RUN npm install -g serve

# Expose port
EXPOSE 3000

# Start the application
CMD ["serve", "-s", "build", "-l", "3000"]